<template>
  <div class="user">
    <!-- 面包屑区域 -->
    <el-breadcrumb separator="/" class="user-tou">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item>
          <el-input
            placeholder="请输入内容"
            v-model="formInline.query"
            class="input-with-select"
            clearable
            @clear="onsubmit"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="onsubmit"
            ></el-button>
          </el-input>
        </el-form-item>
        <!-- 添加用户按钮 -->
        <el-form-item>
          <el-button type="primary" @click="dialogFormVisible = true"
            >添加用户</el-button
          >
        </el-form-item>
        <!-- 列表项 -->
      </el-form>
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column type="index" width="60"> </el-table-column>
        <el-table-column prop="username" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="180">
        </el-table-column>
        <el-table-column prop="create_time" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template #default="{ row }">
            <el-switch
              inactive-color="#ff4949"
              v-model="row.mg_state"
              @change="userswitch(row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="mg_state" label="操作">
          <!-- @click="handleDelete(scope.$index, scope.row)" -->
          <template #default="{ row }">
            <!-- //修改按钮 -->
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="showanniu(row)"
            ></el-button>
            <el-button
              icon="el-icon-delete"
              size="mini"
              type="danger"
              @click="shan(row)"
            ></el-button>
            <!-- 分配角色 -->
            <el-button
              icon="el-icon-setting"
              size="mini"
              type="warning"
              @click="setusers(row)"
            ></el-button>
          </template>
          <!-- <el-button type="primary" icon="el-icon-edit"></el-button>
          <el-button type="danger" icon="el-icon-delete"></el-button>
          <el-button type="warning" icon="el-icon-setting"></el-button> -->
        </el-table-column>
      </el-table>
      <!-- 页码 -->
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes="[1, 2, 5, 10]"
          :page-size="formInline.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :current-page="formInline.pagenum"
        >
          <!-- //使用了size-change和current-change事件来处理页码大小和当前页变动时候触发的事件。 -->
        </el-pagination>
      </div>
    </el-card>
    <!-- 添加用户对话框 -->

    <el-dialog
      title="添加用户"
      :visible.sync="dialogFormVisible"
      @close="adddialog"
    >
      <el-form :model="form" ref="addFormref" :rules="addFormrules">
        <el-form-item
          label="用户名"
          :label-width="formLabelWidth"
          prop="username"
        >
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item
          label="密码"
          :label-width="formLabelWidth"
          prop="password"
        >
          <el-input v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
          <el-input v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" :label-width="formLabelWidth" prop="mobile">
          <el-input v-model="form.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addVisible">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="showVisible"
      width="50%"
      @close="showanniuClose"
    >
      <el-form :model="xiufrom" ref="showFormref" :rules="xiuFormrules">
        <el-form-item label="用户名" :label-width="formLabelWidth">
          <el-input v-model="xiufrom.username" :disabled="true"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
          <el-input v-model="xiufrom.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" :label-width="formLabelWidth" prop="mobile">
          <el-input v-model="xiufrom.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showVisible = false">取 消</el-button>
        <el-button type="primary" @click="showVisibleque">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 分配角色的对话框 -->
    <el-dialog
      title="分配角色"
      @close="setuserclosed"
      :visible.sync="usersVisible"
      width="50%"
    >
      <div>
        <p>当前用户：{{ user.username }}</p>
        <p>当前角色：{{ user.role_name }}</p>
        分配新角色：
        <el-select v-model="valueuser" placeholder="请选择">
          <!-- valueuser 保存已选中角色id -->
          <el-option
            v-for="item in rolelist"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="usersVisible1">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getArticlelist,
  getArticleswitch,
  getArticledialog,
  getArticlxiu,
  getArticlxiushow,
  getArticlshan,
  getroles,
  fenusers,
} from "@/api/article";
export default {
  name: "LoginIndex",
  data() {
    //邮箱手机号验证
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (regEmail.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法邮箱"));
    };
    var checkmobile = (rule, value, cb) => {
      const regmobile =
        /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regmobile.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法手机号"));
    };

    return {
      // 搜索框搜索内容
      formInline: {
        query: "", //用户名
        pagenum: 1, //当前页码数
        pagesize: 1, //当前页数据条数
      },
      //前往第几页
      // currentpage: "2",
      tableData: [],
      value1: true,
      total: 0,

      //添加用户弹框添加隐藏
      dialogFormVisible: false,
      //添加用户表单数据
      form: {
        username: "123123",
        password: "12143143",
        email: "admin55@itcast.cn",
        mobile: "13140203624",
      },
      formLabelWidth: "100px",
      //校验
      addFormrules: {
        username: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur",
          },
          {
            min: 3,
            max: 10,
            message: "用户名长度在3-10个字符之间",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
          {
            min: 3,
            max: 10,
            message: "用户名长度在6-15个字符之间",
            trigger: "blur",
          },
        ],
        email: [
          {
            required: true,
            message: "请输入邮箱",
            trigger: "blur",
          },
          {
            validator: checkEmail,
            trigger: "blur",
          },
        ],
        mobile: [
          {
            required: true,
            message: "请输入手机号",
            trigger: "blur",
          },
          {
            validator: checkmobile,
            trigger: "blur",
          },
        ],
      },
      //修改校验
      xiuFormrules: {
        email: [
          {
            required: true,
            message: "请输入邮箱",
            trigger: "blur",
          },
          {
            validator: checkEmail,
            trigger: "blur",
          },
        ],
        mobile: [
          {
            required: true,
            message: "请输入手机号",
            trigger: "blur",
          },
          {
            validator: checkmobile,
            trigger: "blur",
          },
        ],
      },
      //控制用户修改对话弹框
      showVisible: false,
      //查询用户信息对象
      xiufrom: {},
      //控制角色对话框的显示和隐藏
      usersVisible: false,
      //被分配角色用户信息
      user: {},
      //所有角色数据列表
      rolelist: [],
      //保存选中角色的id值展示在selsct选择器中
      valueuser: "",
    };
  },
  created() {
    this.initdata();
  },
  methods: {
    //搜索框点击事件
    onsubmit() {
      console.log("submit");
      this.initdata();
    },
    // 页码调用
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.formInline.pagesize = val;
      this.initdata();
    },
    //监听页码值
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.formInline.pagenum = val;

      this.initdata();
    },
    async initdata() {
      const res = await getArticlelist({
        query: this.formInline.query,
        pagenum: this.formInline.pagenum,
        pagesize: this.formInline.pagesize,
      });
      this.tableData = res.data.users;
      this.total = res.data.total;

      // console.log(res);
    },
    // 添加用户弹框事件
    adddialog() {
      this.$refs.addFormref.resetFields();
    },
    //点击按钮，添加新用户
    addVisible() {
      this.$refs.addFormref.validate(async (valid) => {
        // console.log(valid); //true
        if (!valid) return;
        const res = await getArticledialog(this.form);
        console.log(res);
        if (res.meta.status !== 201) {
          this.$message.error("添加用户失败");
        }
        this.$message.success("添加用户成功");
      });
      //隐藏添加用户对话框
      this.dialogFormVisible = false;
      //重新获取用户列表数据
      this.initdata();
    },
    //状态修改
    async userswitch(user) {
      // console.log(user);
      const res = await getArticleswitch({
        id: user.id,
        mg_state: user.mg_state,
      });
      console.log(res);
      if (res.meta.status !== 200) {
        user.mg_state = !user.mg_state;
        return this.$message.error("更新用户状态失败！");
      }
      this.$message.success("更新用户状态成功！");
    },
    //展示编辑用户对话框
    async showanniu(id) {
      console.log(id);
      const res = await getArticlxiu(id);
      // console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("查询用户失败");
      }
      //获取的数据 给到设置的空对象里
      console.log(res);
      this.xiufrom = res.data;
      this.showVisible = true;
    },
    //监听修改用户对话框关闭事件
    showanniuClose() {
      this.$refs.showFormref.resetFields();
    },
    //编辑修改用户信息
    showVisibleque() {
      this.$refs.showFormref.validate(async (valid) => {
        console.log(valid);
        if (!valid) return;
        // console.log(this.xiufrom);

        // 发起修改用户信息的数据请求
        const res = await getArticlxiushow({
          id: this.xiufrom.id,
          email: this.xiufrom.email,
          mobile: this.xiufrom.mobile,
        });
        console.log(res);
        if (res.meta.status !== 200) {
          return this.$message.error("更新用户信息失败");
        }
        //关闭对话框
        this.showVisible = false;
        //刷新数据列表
        this.initdata();
        //提示修改成功
        this.$message.success("用户信息更新成功");
      });
    },
    //根据id删除对应用户信息
    async shan(id) {
      console.log(id);
      const res = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      if (res !== "confirm") {
        return this.$message.info("已取消删除");
      }
      const shan = await getArticlshan(id);
      console.log(shan);
      if (shan.meta.status !== 200) {
        return this.$message.error("删除用户失败");
      }
      this.$message.success("删除用户成功");
      this.initdata();
    },
    //展示分配角色的对话框
    async setusers(userinfo) {
      // console.log(userinfo);//当前点击用户信息
      this.user = userinfo; //点击获取的用户信息给创建的空对象
      //让展示对话框之前，获取所有角色
      const res = await getroles();
      // console.log(res);
      //把所有角色数据列表给空数组
      this.rolelist = res.data;
      this.usersVisible = true;
    },
    //点击按钮分配角色
    //判断用户是否选择一个新的角色,是不是valueuser已经保存的角色，是则提示用户
    async usersVisible1() {
      // console.log(this.valueuser);//31
      // console.log(this.user);//当前选择的角色所有数据
      if (!this.valueuser) {
        return this.$message.error("请选择要分配的角色");
      }
      //把用户id和当前点击角色id请求接口传过去
      const res = await fenusers(this.user.id, {
        rid: this.valueuser,
      });
      if (res.meta.status !== 200) {
        return this.$message.error("更新角色失败");
      }
      this.$message.success("更新角色成功");
      //更新数据
      this.initdata();
      //关闭对话框
      this.usersVisible = false;
    },
    //监听分配角色对话框关闭事件
    setuserclosed() {
      (this.valueuser = ""), (this.user = {});
    },
  },
};
</script>

<style lang="less" scoped>
.user-tou {
  margin-bottom: 15px;
}
</style>
